<?php
namespace App\Http\Controllers\Gateway;

use App\Http\Controllers\Controller;
use App\Lib\GatewayCode;
use App\Models\RechargeOrder;
use App\Services\GatewayResponseService;
use App\Services\ThirdPayments\Contracts\Actions\ActionAbstract;
use App\Services\ThirdPayments\Contracts\Actions\HrefRedirectAction;
use App\Services\ThirdPayments\Contracts\Actions\QrCodeAction;
use App\Services\ThirdPayments\Contracts\QRCapable;
use App\Services\ThirdPayments\Contracts\RechargePaymentFactory;
use App\Services\ThirdPayments\Contracts\SDKable;
use App\Services\ThirdPayments\Contracts\WAPable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CheckoutController extends Controller
{
    protected $thirdIf;
    protected $orderInfo;

    public function __construct(Request $request,
                                RechargePaymentFactory $rechargePaymentFactory)
    {
        $merchantNo = $request->input('merchantNo');
        $this->orderInfo = RechargeOrder::bymchno($merchantNo)->firstOrFail();
        $recharge_if =  $this->orderInfo->upperIf;
        $this->thirdIf = $rechargePaymentFactory->getInstance($recharge_if);
    }

    public function qrCode(Request $request)
    {
        if ($this->thirdIf instanceof QRCapable) {
            $qrSrc = $this->thirdIf->qrCode($this->orderInfo);
            if ($qrSrc instanceof QrCodeAction) {
                $redisData = [
                    'qrCode' => $qrSrc->render(),
                    'orderInfo' => $this->orderInfo
                ];
                Redis::setEx('qrcode:'.$this->orderInfo->plat_no, 5 * 60 , json_encode($redisData));
                return redirect()->route('gateway.recharge.qrcode.show', ['plat_no' => $this->orderInfo->plat_no]);
            } else if ($qrSrc instanceof HrefRedirectAction) {
                return $qrSrc->render();
            }
        } else {
            return redirect($this->thirdIf->scanCode($this->orderInfo));
        }
    }

    public function bankHref(Request $request)
    {
        $href = $this->thirdIf->bankHref($this->orderInfo);
        return redirect($href);
    }

    public function wap(Request $request)
    {
        if ($this->thirdIf instanceof WAPable) {
            $result = $this->thirdIf->wapReq($this->orderInfo);
            if ($result instanceof ActionAbstract) {
                return $result->render();
            } else {
                return $result;
            }
        } else {
            return GatewayResponseService::codeError(GatewayCode::THIRD_IF_INVALID);
        }
    }

    public function sdk(Request $request)
    {
        $third_if = $this->thirdIf;
        if ($third_if instanceof SDKable) {
            $third_if->sdkReq($this->orderInfo);
        } else {
            return GatewayResponseService::codeError(GatewayCode::THIRD_IF_INVALID);
        }
    }
}
